#include "SnakePch.h"
#include "DSnakeManager.h"
#include "DSnake.h"

DSnakeManager::DSnakeManager()
	:m_pConnector(NULL)
{

}

DSnakeManager::~DSnakeManager()
{

}

bool DSnakeManager::Init( void* pConnector )
{
	bool	bResult	= false;

	//Log(pConnector != NULL);

	m_pConnector = static_cast<snake::ISnakeConnector*>(pConnector);
	//Log(m_pConnector != NULL);

	bResult = true;
Exit0:
	return bResult;
}

void DSnakeManager::UnInit()
{
	for(MAP_SNAKE::iterator it = m_mapSnake.begin(); it != m_mapSnake.end(); )
	{
		it->second->UnInit();
		delete it->second;
	}

	m_mapSnake.clear();
}

void DSnakeManager::Release()
{
	delete this;
}

void DSnakeManager::Tick()
{
	for(MAP_SNAKE::iterator it = m_mapSnake.begin(); it != m_mapSnake.end(); ++it)
	{
		// Do Something
	}
}

ISnake* DSnakeManager::AddSnake( DWORD dwID )
{
	bool			bResult		= false;
	DSnake*			pSnake		= NULL;
	bool			bInit		= false;
	DWORD			dwSnakeID	= dwID;
	MAP_SNAKE_RET	ret;

	if(dwSnakeID == ERROR_ID)
	{
		//bRetCode = GenerateID(ID_SNAKE, &dwSnakeID);
		//Log(bRetCode);
	}

	pSnake = new DSnake(dwSnakeID);
	//Log(pSnake);

	bInit = pSnake->Init(m_pConnector);
	//Log(bInit);

	ret = m_mapSnake.insert(std::make_pair(dwSnakeID, pSnake));
	//Log(ret.second);

	bResult = true;
Exit0:
	if(!bResult)
	{
		if(bInit)
			pSnake->UnInit();
		if(pSnake)
			delete pSnake;

		pSnake = NULL;
	}
	return pSnake;
}

ISnake* DSnakeManager::GetSnake( DWORD dwID )
{
	ISnake*				pSnake	= NULL;
	MAP_SNAKE::iterator it;

	it = m_mapSnake.find(dwID);
	//Log(it != m_mapSnake.end());

	pSnake = it->second;

Exit0:
	return pSnake;
}

bool DSnakeManager::DelSnake( DWORD dwID )
{
	bool				bResult	= false;
	MAP_SNAKE::iterator it;

	it = m_mapSnake.find(dwID);
	//Log(it != m_mapSnake.end());

	it->second->UnInit();
	delete it->second;

	m_mapSnake.erase(it);

	bResult = true;
Exit0:
	return bResult;
}
